import random
from django.http import JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import login
from game.models.settings.player.player import Player
from django.core.cache import cache
import requests
from django.shortcuts import redirect
def receive_code(resp):
    
    state = resp.GET.get('state');

    if not cache.has_key(state):
        return redirect('index');

    cache.delete(state)

    code = resp.GET.get('code');
    appid = '2156'
    secret= '87da0c5e1a044d3e836ce6d1a3113a30'
    url = 'https://www.acwing.com/third_party/api/oauth2/access_token/';
    kv = {

        'code': code,
        'appid': appid,
        'secret': secret,

            }

    data = requests.get(url,params = kv).json();
    access_token = data['access_token']
    refresh_token = data['refresh_token']
    openid = data['openid']
    player = Player.objects.filter(openid=openid)
    
    if player.exists():
        user = player[0].user
    else:
        url = 'https://www.acwing.com/third_party/api/meta/identity/getinfo/'
        kv = {
            'access_token': access_token,
            'openid': openid
                }
        data = requests.get(url,params=kv).json()
        username = data['username']
        photo = data['photo']

        while User.objects.filter(username = username).exists():
            username += str(random.randint(0,9));

        user = User.objects.create(username=username)
        player = Player.objects.create(user=user,photo=photo,openid=openid)


    login(resp,user);

    return redirect('index');
